<template>
  <view class="health-input-page">
    <!-- 顶部导航 -->
<!--    <view class="page-navbar">
      <view class="nav-left" @click="handleNavigateBack">
        <wd-icon name="arrow-left" size="24rpx" color="#333"></wd-icon>
        <text class="nav-text">返回</text>
      </view>
      <text class="nav-title">健康数据录入</text>
      <view class="nav-right" @click="handleSubmit">
        <text class="submit-btn">提交</text>
      </view>
    </view> -->

    <!-- 内容区域 -->
    <!-- <scroll-view class="content-container" scroll-y> -->
      <!-- 数据类型选择 -->
      <view class="form-item">
        <text class="date-label label">数据类型</text>
        <picker 
          mode="selector" 
          :range="dataTypeList" 
          :range-key="'text'" 
          :value="selectedTypeIndex" 
          @change="handleDataTypeChange"
        >
          <view class="picker-view">
            {{ selectedType?.text || '请选择数据类型' }}
            <wd-icon name="arrow-down" size="20rpx" color="#999"></wd-icon>
          </view>
        </picker>
      </view>

      <!-- 单个日期选择器（替换原时间范围） -->
      <view class="form-item">
        <text class="select-label label">选择测量日期</text>
       <wd-datetime-picker 
         v-model="dateTimeValue" 
         :formatter="formatter" 
         mode="datetime"  
       />
      </view>

      <!-- 数值输入区域（动态根据数据类型变化） -->
      <view class="form-item">
        <text class="label">测量数值</text>
        <view class="input-group">
          <!-- 血压（收缩压/舒张压） -->
          <template v-if="selectedType?.value === '血压'">
            <input 
              type="number" 
              placeholder="请输入收缩压（mmHg）" 
              v-model.number="inputValue.systolic"
              class="input-field"
            >
            <text class="unit">/</text>
            <input 
              type="number" 
              placeholder="请输入舒张压（mmHg）" 
              v-model.number="inputValue.diastolic"
              class="input-field"
            >
          </template>

          <!-- 血糖（mmol/L） -->
          <template v-else-if="selectedType?.value === '血糖'">
            <input 
              type="number" 
              placeholder="请输入血糖值（mmol/L）" 
              v-model.number="inputValue.bloodSugar"
              class="input-field"
            >
          </template>

          <!-- 心率（次/分钟） -->
          <template v-else-if="selectedType?.value === '心率'">
            <input 
              type="number" 
              placeholder="请输入心率值（次/分钟）" 
              v-model.number="inputValue.heartRate"
              class="input-field"
            >
          </template>

          <!-- 体温（℃） -->
          <template v-else-if="selectedType?.value === '体温'">
            <input 
              type="number" 
              placeholder="请输入体温值（℃）" 
              v-model.number="inputValue.temperature"
              class="input-field"
            >
          </template>

          <!-- 血氧（%） -->
          <template v-else-if="selectedType?.value === '血氧'">
            <input 
              type="number" 
              placeholder="请输入血氧饱和度（%）" 
              v-model.number="inputValue.oxygenSaturation"
              class="input-field"
            >
          </template>
        </view>
      </view>

      <!-- 备注输入 -->
      <view class="form-item">
        <text class="label">备注信息</text>
        <textarea 
          placeholder="请输入测量时的备注（可选）" 
          v-model="remark"
          class="remark-textarea"
        ></textarea>
      </view>
	  
	  <view class="button-view">
		  <wd-button block>提交</wd-button>
	  </view>
    <!-- </scroll-view> -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 静态数据类型配置
const dataTypeList = ref([
  { text: '血压', value: '血压' },
  { text: '血糖', value: '血糖' },
  { text: '心率', value: '心率' },
  { text: '体温', value: '体温' },
  { text: '血氧', value: '血氧' }
]);

// 单个日期值（初始化为当前日期）
const dateTimeValue = ref(Date.now());
// 日期格式化函数
const formatter = (type, value) => {
  switch (type) {
    case 'year': return `${value}年`;
    case 'month': return `${value}月`;
    case 'date': return `${value}日`;
    case 'hour': return `${value}时`;
    case 'minute': return `${value}分`;
    case 'second': return `${value}秒`;
    default: return value;
  }
};

// 选中的数据类型索引
const selectedTypeIndex = ref(0);
// 选中的数据类型对象
const selectedType = computed(() => {
  return dataTypeList.value[selectedTypeIndex.value] || {};
});

// 输入数值（根据数据类型动态变化）
const inputValue = ref({
  systolic: '',       // 收缩压
  diastolic: '',      // 舒张压
  bloodSugar: '',     // 血糖
  heartRate: '',      // 心率
  temperature: '',    // 体温
  oxygenSaturation: ''// 血氧
});

// 备注信息
const remark = ref('');

// 生命周期：页面加载时初始化日期为今天（修复：闭合大括号）
onMounted(() => {
  dateTimeValue.value = Date.now(); // 初始化为当前时间戳（wd-datetime-picker默认支持）
}); // 关键修复：补充闭合大括号

// 数据类型选择变化
const handleDataTypeChange = (e) => {
  selectedTypeIndex.value = e.detail.value;
  // 切换类型时清空输入
  inputValue.value = {
    systolic: '',
    diastolic: '',
    bloodSugar: '',
    heartRate: '',
    temperature: '',
    oxygenSaturation: ''
  };
};

// 提交数据
const handleSubmit = () => {
  // 输入验证
  if (!validateInput()) return;

  // 构造提交数据（日期转换为ISO格式字符串）
  const submitData = {
    type: selectedType.value.value,
    date: new Date(dateTimeValue.value).toISOString().split('T')[0], // 格式化为 YYYY-MM-DD
    value: { ...inputValue.value },
    remark: remark.value.trim()
  };

  // 这里调用实际接口（示例用uni.request）
  uni.request({
    url: '/api/health-data/submit',
    method: 'POST',
    data: submitData,
    success: (res) => {
      if (res.data.code === 200) {
        uni.showToast({ title: '提交成功', icon: 'success' });
        setTimeout(() => uni.navigateBack(), 1500);
      } else {
        uni.showToast({ title: '提交失败：' + res.data.msg, icon: 'none' });
      }
    },
    fail: () => {
      uni.showToast({ title: '网络请求失败', icon: 'none' });
    }
  });
};

// 输入验证逻辑（简化版，仅保留核心验证）
const validateInput = () => {
  // 验证数据类型是否选择
  if (!selectedType.value.value) {
    uni.showToast({ title: '请选择数据类型', icon: 'none' });
    return false;
  }

  // 验证日期是否选择（wd-datetime-picker默认必选，此处可选添加额外验证）
  if (!dateTimeValue.value) {
    uni.showToast({ title: '请选择测量日期', icon: 'none' });
    return false;
  }

  // 根据数据类型验证具体数值（与原逻辑一致）
  switch (selectedType.value.value) {
    case '血压':
      if (!inputValue.value.systolic || !inputValue.value.diastolic) {
        uni.showToast({ title: '请填写完整的收缩压和舒张压', icon: 'none' });
        return false;
      }
      if (Number(inputValue.value.systolic) <= Number(inputValue.value.diastolic)) {
        uni.showToast({ title: '收缩压应大于舒张压', icon: 'none' });
        return false;
      }
      break;
      
    case '血糖':
      if (!inputValue.value.bloodSugar) {
        uni.showToast({ title: '请填写血糖值', icon: 'none' });
        return false;
      }
      break;
      
    // 其他数据类型验证逻辑...
  }

  return true;
};

// 返回上一页
const handleNavigateBack = () => {
  uni.navigateBack();
};

// 修复：补充 relationOptions、selectedRelationIndex、selectedRelation 的定义（原代码可能遗漏）
const relationOptions = ref([
  { text: '子女', value: '子女' },
  { text: '配偶', value: '配偶' },
  { text: '父母', value: '父母' },
  { text: '其他亲属', value: '其他亲属' },
  { text: '护工', value: '护工' }
]);

const selectedRelationIndex = ref(0);
const selectedRelation = computed(() => {
  return relationOptions.value[selectedRelationIndex.value] || {};
});
</script>

<style lang="scss" scoped>
.health-input-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #eef2f6 100%);
  padding: 0 30rpx;
  padding-bottom: 40rpx;
  padding-top: 50rpx;

  .page-navbar {
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 16rpx;
    margin-bottom: 24rpx;
    border-bottom: none;

    .nav-left {
      display: flex;
      align-items: center;
      gap: 8rpx;

      .nav-text {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
      }
    }

    .nav-title {
      flex: 1;
      text-align: center;
      font-size: 34rpx;
      font-weight: 600;
      color: #1a1a1a;
      letter-spacing: 0.5rpx;
    }

    .nav-right {
      .submit-btn {
        color: #1890ff;
        font-size: 32rpx;
        font-weight: 500;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
        transition: all 0.2s;

        &:active {
          background: rgba(24, 144, 255, 0.1);
          opacity: 0.9;
        }
      }
    }
  }

  .content-container {
    height: calc(100vh - 88rpx - 40rpx);
    padding: 0;
  }

  .form-item {
    margin-bottom: 36rpx;
    padding: 0 8rpx;

    .label {
      display: block;
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 24rpx;
      letter-spacing: 0.3rpx;
    }
  }

  .picker-view, wd-datetime-picker {
    height: 72rpx;
    background: #fff;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transition: all 0.2s;
    border: 1rpx solid #e5e7eb;

    &:active {
      border-color: #1890ff;
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.1);
    }

    .wd-icon {
      opacity: 0.7;
      transition: all 0.2s;
      flex-shrink: 0;
    }
  }

  .picker-view {
	  padding-left: 30rpx;
    .label-text {
      margin-right: 12rpx;
    }
  }

  wd-datetime-picker {
    .datetime-picker__label {
      margin-right: 16rpx;
      font-size: 28rpx;
      color: #333;
    }

    .datetime-picker__input {
      flex: 1;
      height: 100%;
      padding: 0 8rpx;
      &::placeholder {
        color: #bfbfbf;
      }
    }
  }

  .input-group {
    display: flex;
    align-items: center;
    gap: 12rpx;
    height: 72rpx;
    background: #fff;
    border-radius: 12rpx;
    border: 1rpx solid #e5e7eb;
    padding: 0 16rpx;
    transition: all 0.2s;

    &:active {
      border-color: #1890ff;
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.1);
    }

    .input-field {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
      color: #333;
      border: none;
      outline: none;
      background: transparent;
      padding: 0 12rpx;
      &::placeholder {
        color: #bfbfbf;
      }
    }

    .unit {
      color: #999;
      font-size: 28rpx;
      font-weight: 500;
      padding: 0 4rpx;
    }
  }

  .remark-textarea {
    width: 100%;
    height: 140rpx;
	box-sizing: border-box;
    padding: 16rpx;
    background: #fff;
    border-radius: 12rpx;
    border: 1rpx solid #e5e7eb;
    font-size: 28rpx;
    color: #333;
    resize: none;
    outline: none;
    transition: all 0.2s;

    &:active {
      border-color: #1890ff;
      box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.1);
    }

    &::placeholder {
      color: #bfbfbf;
    }
  }
}

:deep(.wd-cell) {
  border-radius: 16rpx!important;
  border: 1rpx solid #e5e7eb!important;
}

:deep(.wd-icon-arrow-down) {
  font-size: 32rpx!important;
  padding-right: 30rpx;
}
.button-view{
	margin-top:50rpx;
}
</style>